/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package th.stripes.resources;

import com.google.inject.Inject;
import java.util.Date;
import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import th.manager.UserManager;
import th.model.Pengguna;
import th.service.session.LoginSession;
import th.service.session.SessionManager;
import th.stripes.BaseActionBean;

/**
 *
 * @author fikri
 */
@UrlBinding("/services/logout")
public class LogoutResource extends BaseActionBean implements iRest{

    
    @Inject UserManager userManager;
    
    @HandlesEvent("user_logout")
    public Resolution logout() {
        
        HttpSession ses = getContext().getRequest().getSession();
        String id = getContext().getRequest().getHeader("Cookie"); 
        String[] sessAuth = id.substring(id.indexOf("=")+1).split(":");
        
        String sessId = "";
        String userId = "";
        
        if (sessAuth.length > 0) {
            sessId = sessAuth[0];
            userId = sessAuth[1];
            
             SessionManager sm = SessionManager.getInstance();
             LoginSession ls = sm.getActiveSessionByUserId(userId);
             if (ls == null) return new StreamingResolution("text/plain","Maaf, sessi sudah luput.");             
             
                sm.removeSession(sessId);
                _logout();
                if (ses != null) {
                    ses.invalidate();
                }
            
        }      
        

//        Date d = (Date)ses.getAttribute("_TRH_LOGIN"); 
//        if ( d != null) {
//            pengguna.setTarikhAkhirLogin(d);
//            userManager.updatePengguna(pengguna);
//        }
        
        
        
        return new StreamingResolution("application/json",toJson());
    }
    
    public String toJson() {
        return "";
    }
    
    private void _logout() {
        getContext().logout();
        addMessage("loggedOut");
    }
    
}
